/*
 * Copyright 2011 Daniel Centore
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */
package motej.centore;

import java.util.ArrayList;
import java.util.List;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.LocalDevice;

import com.intel.bluetooth.BlueCoveImpl;

/**
 * Handles rotation of the dongles. Basically, every time a new WiiMote is
 * connected it switches to the next dongle for searching
 * 
 * @author Daniel Centore
 * 
 */
public class RotationController
{
	private static List<Dongle> dongles = new ArrayList<Dongle>(); // List of all dongles present at program start

	private static volatile boolean initialized = false; // Have we initialized the RotationController yet?
	private static volatile int id = 0; // What id did we last use?

	/**
	 * Sets the next dongle on the list
	 * @return The ID of that dongle
	 */
	public static synchronized Object setNextDongle()
	{
		BlueCoveImpl.releaseThreadBluetoothStack();
		BlueCoveImpl.useThreadLocalBluetoothStack();

		Dongle id = getNextDongle();
		BlueCoveImpl.setThreadBluetoothStackID(id.getId());

		return id.getId();
	}

	private static synchronized Dongle getNextDongle() // helper
	{
		id++;
		if (id >= dongles.size())
			id = 0;

		return dongles.get(id);
	}

	/**
	 * Initializes the dongles
	 * @throws BluetoothStateException If something goes wrong
	 */
	public static void initializeDongles() throws BluetoothStateException
	{
		if (initialized)
		{
			//			System.out.println("Dongles already initialized!");
			return;
		}

		BlueCoveImpl.useThreadLocalBluetoothStack();

		boolean done = false;

		List<String> q = new ArrayList<String>();

		int i = 0;
		while (!done)
		{
			try
			{
				BlueCoveImpl.setConfigProperty("bluecove.deviceID", i + "");

				try
				{
					q.add(LocalDevice.getLocalDevice().getBluetoothAddress());
				} catch (UnsatisfiedLinkError e)
				{
					e.printStackTrace();
					System.out.println("Make sure libbluetooth-dev is installed");
				}

				dongles.add(new Dongle(BlueCoveImpl.getThreadBluetoothStackID()));

				BlueCoveImpl.releaseThreadBluetoothStack();

				i++;
			} catch (Exception e)
			{
				done = true; // called when bt device no longer exists
			}
		}

		NewLogger.println("-------------------");
		for (String s : q)
			NewLogger.println("Device [" + s + "] initialized.");

		NewLogger.println("Total of [" + i + "] devices found."); //not i-1 b/c we start counting at 0

		initialized = true;
	}

}
